//
//  CameraViewController.m
//  自定义美颜
//
//  Created by zhao on 16/8/1.
//  Copyright © 2016年 zhao. All rights reserved.
//

#import "CameraViewController.h"
#import "GPUImageBeautifyFilter.h"
#import "DFCamerPreView.h"


/////滤镜View的显示状态
typedef NS_ENUM(NSInteger, FilterViewState) {
    
    FilterViewHidden,/**<隐藏*/
    
    FilterViewUsing /**<显示*/
};
///闪光灯状态
typedef NS_ENUM(NSInteger, CameraManagerFlashMode) {
    
    CameraManagerFlashModeOff, /**<关闭*/
    
    CameraManagerFlashModeOn, /**<打开*/
    
    CameraManagerFlashModeAuto /**<自动*/
};


@interface CameraViewController ()<UIGestureRecognizerDelegate,DFCamerPreViewDelegate>

{
    GPUImageView        *_frameView;    /// 图像框
    GPUImageBeautifyFilter *_beautifyFilter; /// 美颜滤镜
    CALayer *_focusLayer; //聚焦层
}

/**新建相机cameraManager*/
@property (nonatomic,strong) GPUImageStillCamera *cameraManager;

@property (nonatomic , assign) CameraManagerFlashMode flashMode;//闪光灯模式
@property (nonatomic , assign) FilterViewState filterViewState;//滤镜视图显示状态

@property (nonatomic , assign) CGFloat beginGestureScale;//开始的缩放比例
@property (nonatomic , assign) CGFloat effectiveScale;//最后的缩放比例
@property (weak, nonatomic)  DFCamerPreView *camerPreView;//相机预览图

@end

@implementation CameraViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupCamerPreView];
    
    [self beautifyVideo];
    
}
/**初始化相机预览图层*/
- (void)setupCamerPreView {
    DFCamerPreView *camerPreView = [[DFCamerPreView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    camerPreView.delegate = self;
    self.camerPreView = camerPreView;
    [self.view addSubview:self.camerPreView];
}
/**设置美颜滤镜*/
- (void)beautifyVideo {
    
    _cameraManager = [[GPUImageStillCamera alloc]initWithSessionPreset:AVCaptureSessionPresetHigh cameraPosition:AVCaptureDevicePositionFront];
    _cameraManager.outputImageOrientation = UIInterfaceOrientationPortrait;
    _cameraManager.horizontallyMirrorFrontFacingCamera = YES;
    [self setfocusImage:[UIImage imageNamed:@"shift"]];//初始化聚焦图片
    
    _beautifyFilter = [[GPUImageBeautifyFilter alloc]init];
    
    _frameView = [[GPUImageView alloc]init];
    
    [_beautifyFilter addTarget:_frameView];
    [_cameraManager addTarget:_beautifyFilter];
    
    [self.camerPreView addSubview:_frameView];
    //初始化闪光灯模式为Auto
    [self setFlashMode:CameraManagerFlashModeAuto];
    //默认滤镜视图为隐藏，就是点击滤镜的按钮才会出现让你选择滤镜的那个小视图
    [self setFilterViewState:FilterViewHidden];
    
    [_cameraManager startCameraCapture];
}
- (void)viewDidLayoutSubviews {
    
    _frameView.frame = self.camerPreView.bounds;
    [self.camerPreView bringSubviewToFront:self.camerPreView.setupView];
    
}

#pragma mark 闪光灯设置
//设置闪光灯模式
- (void)setFlashMode:(CameraManagerFlashMode)flashMode {
    _flashMode = flashMode;
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch] && [device hasFlash]){
        [device lockForConfiguration:nil];
        switch (flashMode) {
            case CameraManagerFlashModeAuto: {
                if ([device isFlashModeSupported:AVCaptureFlashModeAuto]) {
                    [device setFlashMode:AVCaptureFlashModeAuto];
                    [device unlockForConfiguration];
                }
            }
                break;
            case CameraManagerFlashModeOff: {
                
                [device setFlashMode:AVCaptureFlashModeOff];
                [device unlockForConfiguration];
            }
                break;
            case CameraManagerFlashModeOn: {
                [device setFlashMode:AVCaptureFlashModeOn];
                [device unlockForConfiguration];
            }
                break;
                
            default:
                break;
        }
    }
}

#pragma mark 改变闪光灯状态
- (void)changeFlashMode:(UIButton *)button {
    switch (self.flashMode) {
        case CameraManagerFlashModeAuto:
            self.flashMode = CameraManagerFlashModeOn;
            [button setImage:[UIImage imageNamed:@"flashing_on"] forState:UIControlStateNormal];
            [button setTitle:@"⚡️打开" forState:UIControlStateNormal];
            break;
        case CameraManagerFlashModeOff:
            self.flashMode = CameraManagerFlashModeAuto;
            [button setImage:[UIImage imageNamed:@"flashing_auto"] forState:UIControlStateNormal];
            [button setTitle:@"⚡️自动" forState:UIControlStateNormal];
            break;
        case CameraManagerFlashModeOn:
            self.flashMode = CameraManagerFlashModeOff;
            [button setImage:[UIImage imageNamed:@"flashing_off"] forState:UIControlStateNormal];
            [button setTitle:@"⚡️关闭" forState:UIControlStateNormal];
            break;
            
        default:
            break;
    }
}

#pragma mark - 保存照片
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    if (!error) {
        NSLog(@"%s",__func__);
    }
}

#pragma mark - 调整焦距
//调整焦距方法
-(void)focusDisdance:(UIPinchGestureRecognizer*)pinch {
    self.effectiveScale = self.beginGestureScale * pinch.scale;
    if (self.effectiveScale < 1.0f) {
        self.effectiveScale = 1.0f;
    }
    CGFloat maxScaleAndCropFactor = 3.0f;//设置最大放大倍数为3倍
    if (self.effectiveScale > maxScaleAndCropFactor)
        self.effectiveScale = maxScaleAndCropFactor;
    [CATransaction begin];
    [CATransaction setAnimationDuration:.025];
    NSError *error;
    if([self.cameraManager.inputCamera lockForConfiguration:&error]){
        [self.cameraManager.inputCamera setVideoZoomFactor:self.effectiveScale];
        [self.cameraManager.inputCamera unlockForConfiguration];
    }
    else {
        NSLog(@"ERROR = %@", error);
    }
    [CATransaction commit];
}

//设置聚焦图片
- (void)setfocusImage:(UIImage *)focusImage {
    if (!focusImage) return;
    
    if (!_focusLayer) {
        //增加tap手势，用于聚焦及曝光
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(focus:)];
        [self.camerPreView.setupView addGestureRecognizer:tap];
        //增加pinch手势，用于调整焦距
        UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(focusDisdance:)];
        [self.camerPreView.setupView addGestureRecognizer:pinch];
        pinch.delegate = self;
    }
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, focusImage.size.width * 0.3, focusImage.size.height * 0.3)];
    imageView.image = focusImage;
    CALayer *layer = imageView.layer;
    layer.hidden = YES;
    [self.camerPreView.setupView.layer addSublayer:layer];
    _focusLayer = layer;
    
}
#pragma mark - 手势代理方法
//因为默认是不支持多手势的
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ( [gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] ) {
        self.beginGestureScale = self.effectiveScale;
    }
    return YES;
}
#pragma mark 对焦
//对焦方法
- (void)focus:(UITapGestureRecognizer *)tap {
    self.camerPreView.setupView.userInteractionEnabled = NO;
    CGPoint touchPoint = [tap locationInView:tap.view];
    
    [self layerAnimationWithPoint:touchPoint];
    /**下面是照相机焦点坐标轴和屏幕坐标轴的映射问题*/
    if(_cameraManager.cameraPosition == AVCaptureDevicePositionBack){
        touchPoint = CGPointMake( touchPoint.y /tap.view.bounds.size.height ,1-touchPoint.x/tap.view.bounds.size.width);
    }
    else
        touchPoint = CGPointMake(touchPoint.y /tap.view.bounds.size.height ,touchPoint.x/tap.view.bounds.size.width);
    /*以下是相机的聚焦和曝光设置，前置不支持聚焦但是可以曝光处理，后置相机两者都支持，下面的方法是通过点击一个点同时设置聚焦和曝光，当然根据需要也可以分开进行处理
     */
    if([self.cameraManager.inputCamera isExposurePointOfInterestSupported] && [self.cameraManager.inputCamera isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure])
    {
        NSError *error;
        if ([self.cameraManager.inputCamera lockForConfiguration:&error]) {
            [self.cameraManager.inputCamera setExposurePointOfInterest:touchPoint];
            [self.cameraManager.inputCamera setExposureMode:AVCaptureExposureModeContinuousAutoExposure];
            if ([self.cameraManager.inputCamera isFocusPointOfInterestSupported] && [self.cameraManager.inputCamera isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
                [self.cameraManager.inputCamera setFocusPointOfInterest:touchPoint];
                [self.cameraManager.inputCamera setFocusMode:AVCaptureFocusModeAutoFocus];
            }
            [self.cameraManager.inputCamera unlockForConfiguration];
        } else {
            NSLog(@"ERROR = %@", error);
        }
    }
}

//对焦动画
- (void)layerAnimationWithPoint:(CGPoint)point {
    if (_focusLayer) {
        ///聚焦点聚焦动画设置
        CALayer *focusLayer = _focusLayer;
        focusLayer.hidden = NO;
        [CATransaction begin];
        [CATransaction setDisableActions:YES];
        [focusLayer setPosition:point];
        focusLayer.transform = CATransform3DMakeScale(2.0f,2.0f,1.0f);
        [CATransaction commit];
        
        CABasicAnimation *animation = [ CABasicAnimation animationWithKeyPath: @"transform" ];
        animation.toValue = [ NSValue valueWithCATransform3D: CATransform3DMakeScale(1.0f,1.0f,1.0f)];
        animation.delegate = self;
        animation.duration = 0.3f;
        animation.repeatCount = 1;
        animation.removedOnCompletion = NO;
        animation.fillMode = kCAFillModeForwards;
        [focusLayer addAnimation: animation forKey:@"animation"];
    }
}

//动画的delegate方法
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    //    1秒钟延时
    [self performSelector:@selector(focusLayerNormal) withObject:self afterDelay:0.5f];
}

//focusLayer回到初始化状态
- (void)focusLayerNormal {
    self.camerPreView.setupView.userInteractionEnabled = YES;
    _focusLayer.hidden = YES;
}

#pragma mark - DFCamerPreViewDelegate
/**切换闪光灯*/
- (void)didClickChangeFlashMode:(UIButton *)button {
    
    [self changeFlashMode:button];
}
/**切换前后摄像头*/
- (void)didClickTurnLight:(UIButton *)button {
    
    [_cameraManager rotateCamera];
    
}
/**点击相册预览*/
- (void)didClickphotoBroswBtn:(UIButton *)button {
    
}
/**点击拍照*/
- (void)didClickTakePhoto:(UIButton *)button {
    button.enabled = NO;
    [_cameraManager capturePhotoAsJPEGProcessedUpToFilter:_beautifyFilter withCompletionHandler:^(NSData *processedJPEG, NSError *error) {
        if (!error) {
            UIImage *newImage = [UIImage imageWithData:processedJPEG scale:[UIScreen mainScreen].scale];
            self.camerPreView.currentImage = newImage;
            UIImageWriteToSavedPhotosAlbum(newImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            
            button.enabled = YES;
        }
        NSLog(@"currentThread = %@", [NSThread currentThread]);
    }];
}
/**点击取消*/
- (void)didClickCancelButton:(UIButton *)button {
    
}


-(BOOL)prefersStatusBarHidden {
    
    return YES;
}

@end
